"use strict";
const axios = require("axios");
const cache = require('../cache');
require('dotenv').config(); //默认.env在同一目录

async function genWeappUrlLink(args = {
    path: "/pages/index/index",
    query: "spid=1",
    is_expire: false,
}) {
    const token = await getWechatAccessToken("weapp");
    const { path, query, is_expire } = args;
    const response = await axios.post(
        `https://api.weixin.qq.com/wxa/generate_urllink?access_token=${token}`,
        args
    );
    return response?.data?.url_link ?? null;
}

async function getWechatAccessToken(type = "weapp") {
    const appid = type === "weapp" ?  process.env.IHEAL_WXAPP_APP_ID : process.env.IHEAL_WXMP_APP_ID;
    const secret = type === "weapp" ?  process.env.IHEAL_WXAPP_APP_SECRET : process.env.IHEAL_WXMP_APP_SECRET;
    const key = `IHEAL-${type.toUpperCase()}-ACCESS-TOKEN`;

    try {
        const cachedToken = cache.get(key);
        if (cachedToken) {
            return cachedToken;
        }

        const response = await axios.post(
            "https://api.weixin.qq.com/cgi-bin/stable_token",
            {
                grant_type: "client_credential",
                appid,
                secret,
            }
        );

        if (response?.data?.access_token) {
            const accessToken = response.data.access_token;
            cache.set(key, accessToken, 6800);
            return accessToken;
        }

        throw new Error(`Failed to get access token: ${JSON.stringify(response.data)}`);
    } catch (error) {
        console.error(`Error getting WeChat access token for ${type}:`, error);
        throw error;
    }
}

async function main() {
    const url = await genWeappUrlLink();
    console.log(url);
}

main();
